import {
  useRef,
  PropsWithChildren,
  CSSProperties,
  FC,
  useCallback,
  useEffect,
} from 'react';
import useWatermark from './useWatermark';

export interface WatermarkProps extends PropsWithChildren {
  /**
   * 样式
   */
  style?: CSSProperties;
  /**
   * 类名
   */
  className?: string;
  /**
   * 自定义层级
   */
  zIndex?: string | number;
  /**
   * 宽度
   */
  width?: number;
  /**
   * 高度
   */
  height?: number;
  /**
   * 旋转角度
   */
  rotate?: number;
  /**
   * 水印图片
   */
  image?: string;
  /**
   * 水印文本内容
   */
  content?: string | string[];
  /**
   * 水印字体样式
   */
  fontStyle?: {
    color?: string;
    fontFamily?: string;
    fontSize?: number | string;
    fontWeight?: number | string;
  };
  /**
   * 间距
   */
  gap?: [number, number];
  /**
   * 相对于 container 容器的偏移量
   */
  offset?: [number, number];
  /**
   * 水印挂载dom
   */
  getContainer?: () => HTMLElement;
}

const Watermark: FC<WatermarkProps> = (props) => {
  const {
    className,
    style,
    zIndex,
    width,
    height,
    rotate,
    image,
    content,
    fontStyle,
    gap,
    offset,
  } = props;

  const containerRef = useRef<HTMLDivElement>(null);

  const getContainer = useCallback(() => {
    return props.getContainer ? props.getContainer() : containerRef.current!;
  }, [containerRef.current, props.getContainer]);

  const { generateWatermark } = useWatermark({
    zIndex,
    width,
    height,
    rotate,
    image,
    content,
    fontStyle,
    gap,
    offset,
    getContainer,
  });

  useEffect(() => {
    generateWatermark({
      zIndex,
      width,
      height,
      rotate,
      image,
      content,
      fontStyle,
      gap,
      offset,
      getContainer,
    });
  }, [
    zIndex,
    width,
    height,
    rotate,
    image,
    content,
    JSON.stringify(props.fontStyle),
    JSON.stringify(props.gap),
    JSON.stringify(props.offset),
    getContainer,
  ]);

  return props.children ? (
    <div className={className} style={style} ref={containerRef}>
      {props.children}
    </div>
  ) : null;
};

export default Watermark;
